/*
登陆的路由组件
 */

import React, { Component } from 'react'
import {
  NavBar,
  WingBlank,
  WhiteSpace,
  Button
} from 'antd-mobile'
import { Input, message } from 'antd'
import { connect } from 'react-redux'
import { Redirect } from 'react-router-dom'
import { login } from '../../redux/actions'
import Logo from '../../components/logo/logo'
import { resetUser } from '../../redux/actions'


class Login extends Component {
  state = {
    username: '',  // 用户名
    password: '',  // 密码
    expression: '',
    validate: '',
  }
  componentDidMount() {
    this.renderCode()
  }

  login = () => {
    const { username, password, expression, validate } = this.state
    if (!expression) {
      message.error('验证码不能为空')
      return
    } else if (expression.toLowerCase() !== validate.toLowerCase()) {
      message.error('验证码不正确')
      this.renderCode()
      return
    }
    this.props.login({ username, password })
  }

  handleChange = (name, val) => {
    // 更新状态
    this.setState({
      [name]: val  // 属性名不是name, 而是name变量的值
    })
  }

  toRegister = () => {
    this.props.resetUser()
    this.props.history.replace('/register')
  }
  random = (min, max) => {
    var x = Math.floor(Math.random() * (max - min) + min);//math.floor函数十分重要，他可以将小数转换为整数，避免rgb和数组无法识别
    return x;
  }
  color = (min, max) => {
    var rgb_r = this.random(min, max);
    var rgb_g = this.random(min, max);
    var rgb_b = this.random(min, max);
    return "rgb(" + rgb_r + "," + rgb_g + "," + rgb_b + ")";
  }
  renderCode = () => {
    let result = '';
    const codeNormal = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';//字母库
    let tmp
    const verification = document.getElementById("verification").getContext("2d");    //获取绘图对象
    verification.clearRect(0,0,130,32)
    verification.textBaseline = 'bottom';                  //设置其对于基准线的位置
    for (var i = 0; i < 4; i++) {
      tmp = codeNormal[Math.round(Math.random() * (codeNormal.length - 1))]
      result = result + tmp;
      verification.fillStyle = this.color(50, 160);   //注意字体与背景的颜色随机区间
      verification.font = this.random(18, 22) + 'px SimHei'; //字体大小随机，注意不要过小，便于用户阅读
      var x = 10 + i * 30;                       //每个字符的位置
      var y = this.random(25, 32);
      var deg = this.random(-45, 45);
      verification.translate(x, y);             //改变字符位置
      verification.rotate(deg * Math.PI / 180); //使字符旋转一定角度
      verification.fillText(tmp, 0, 0);
      verification.rotate(-deg * Math.PI / 180);//复位旋转与原点，避免下个字符在原有基础旋转
      verification.translate(-x, -y);
    }//随机获取字母四个
    this.setState({//设置更新状态
      validate: result
    })
  }


  render() {

    const { msg, redirectTo } = this.props.user
    const { username, password, expression } = this.state
    if (redirectTo) {
      return <Redirect to={redirectTo} />
    }
    if (msg) {
      message.error(msg)
      this.props.resetUser()
    }
    return (
      <div>
        <NavBar className='main-header' >大&nbsp;大&nbsp;直&nbsp;聘</NavBar>
        <Logo />
        <WingBlank>
          <WhiteSpace />
          <Input size="large" placeholder='请输入用户名' value={username} onChange={e => {
            this.setState({ username: e.target.value })
          }} addonBefore="用户名:" />
          <WhiteSpace />
          <Input.Password size="large" placeholder='请输入密码' value={password}
            onChange={e => {
              this.setState({ password: e.target.value })
            }} addonBefore=" 密 码 : &nbsp;" />
          <WhiteSpace />
          <Input size="large" placeholder='请输入验证码' value={expression} onChange={e => {
            this.setState({ expression: e.target.value })
          }} addonBefore="验证码:" addonAfter={<canvas onClick={this.renderCode} id="verification" width="130" height="32"></canvas>} />
          <WhiteSpace />

          <Button type='primary' onClick={this.login} className='main-header' >登&nbsp;&nbsp;&nbsp;陆</Button>
          <WhiteSpace />
          <Button onClick={this.toRegister}>注&nbsp;&nbsp;&nbsp;册</Button>
        </WingBlank>
      </div>
    )
  }
}

export default connect(
  state => ({ user: state.user }),
  { login, resetUser }
)(Login)